package com.hmkj.admin.controller.user;

import com.hmkj.admin.controller.BaseController;
import com.hmkj.admin.controller.GenericController;
import com.hmkj.common.entity.ResultEntity;
import com.hmkj.common.entity.dtgrid.DtGrid;
import com.hmkj.common.entity.export.ExportUtils;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.common.utils.ValidateUtils;
import com.hmkj.core.constant.Constants;
import com.hmkj.core.exception.BussinessException;
import com.hmkj.core.model.user.UserModel;
import com.hmkj.core.po.investor.InvestorSimulate;
import com.hmkj.core.po.operate.Agent;
import com.hmkj.core.po.user.User;
import com.hmkj.core.service.investor.InvestorSimulateService;
import com.hmkj.core.service.operate.AgentService;
import com.hmkj.core.service.user.UserService;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;


@Controller
@RequestMapping(BaseController.BASE_URI)
public class UserJsonController extends GenericController<Integer, User> {
    @Resource
    private UserService userService;
    @Resource
    private InvestorSimulateService investorSimulateService;
    @Resource
    private AgentService agentService;

    /**
     * 用户列表json数据
     */
    @ResponseBody
    @RequestMapping("user/json/list")
    @RequiresPermissions("sys:user:list")
    public DtGrid listJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager,Constants.USER);
        return userService.getDtGridList(dtgrid, UserModel.class);
    }


    /**
     * 列表导出
     *
     * @param dtGridPager
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "user/json/export", method = RequestMethod.POST)
    public ResultEntity export(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        ExportUtils.export(request, response, userService.getDtGridListExport(dtGridPager));
        return ok();
    }


    /**
     * 修改用户类型
     * @param id
     * @param type
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateType")
    @RequiresPermissions("sys:user:type:edit")
    public ResultEntity upateUserType(Integer id, Integer type)throws Exception{
        if (!StringUtils.isNotBlank(id)||!StringUtils.isNotBlank(type)){
            throw new BussinessException("参数有误");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            if(type==User.TYPE.T1.code){
                u.setType(User.TYPE.T1.code);
            }else if(type==User.TYPE.T2.code){
                u.setType(User.TYPE.T2.code);
            }else if (type==User.TYPE.T3.code){
                u.setType(User.TYPE.T3.code);
            }
        }));
        return ok();
    }


    /**
     * 修改用户所属代理商
     * @param id
     * @param agentId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateAgent")
    @RequiresPermissions("sys:user:agent:edit")
    public ResultEntity upateAgent(Integer id, Integer agentId)throws Exception{
        if (!StringUtils.isNotBlank(id)||!StringUtils.isNotBlank(agentId)){
            throw new BussinessException("参数有误");
        }
        Agent agent = agentService.selectByPrimaryKey(agentId);
        if(null == agent){
            throw new BussinessException("代理商不存在");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setAgentId(agentId);
            u.setSource(agent.getDomain());
        }));
        return ok();
    }

    /**
     * 修改用户名
     * @param id
     * @param userName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateUserName")
    @RequiresPermissions("sys:user:username:edit")
    public ResultEntity updateUserName(Integer id, String userName)throws Exception{
        if (!StringUtils.isNotBlank(id)){
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(userName)) {
            throw new BussinessException("用户名不能为空");
        }else if(userName.length()>50){
            throw new BussinessException("用户名长度不能大于50位！");
        }else if(!ValidateUtils.isUserName(userName)){
            throw new BussinessException("用户名必须是中英文或数字组合");
        }
        User user = userService.selectByPrimaryKey(id);
        if(StringUtils.isNotBlank(user.getUserName())){
            if(user.getUserName().equals(userName)){
                return ok();
            }
        }
        int count = userService.selectCount(new User(t->{
            t.setUserName(userName);
            t.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if(count>0){
            throw new BussinessException("该用户名已存在");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setUserName(userName);
        }));
        return ok();
    }


    /**
     * 修改用户姓名
     * @param id
     * @param realName
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateRealName")
    @RequiresPermissions("sys:user:realname:edit")
    public ResultEntity updateRealName(Integer id, String realName)throws Exception{
        if (!StringUtils.isNotBlank(id)){
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(realName)) {
            throw new BussinessException("真实姓名不能为空");
        }else if(realName.length()>20){
            throw new BussinessException("真实姓名长度不能大于20个字符");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setRealName(realName);
        }));
        return ok();
    }

    /**
     * 修改用户身份证
     * @param id
     * @param idCard
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateIdCard")
    @RequiresPermissions("sys:user:idcard:edit")
    public ResultEntity upateIdCard(Integer id, String idCard)throws Exception{
        if (!StringUtils.isNotBlank(id)){
            throw new BussinessException("参数有误");
        }
        if (StrUtil.isBlank(idCard)) {
            throw new BussinessException("身份证号码不能为空");
        }else if(idCard.length()<15 || idCard.length()>18){
            throw new BussinessException("身份证号码长度限制在15到18个字符");
        }else if(!ValidateUtils.isCard(idCard)){
            throw new BussinessException("身份证号码格式不正确");
        }
        User user = userService.selectByPrimaryKey(id);
        if(StringUtils.isNotBlank(user.getIdCard())){
            if(user.getIdCard().equals(idCard)){
                return ok();
            }
        }
        int count = userService.selectCount(new User(t->{
            t.setIdCard(idCard);
            t.setDelFlag(User.DELFLAG.NORMAL.code);
        }));
        if(count>0){
            throw new BussinessException("身份证号码已存在，请核对身份证号码是否正确");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setIdCard(idCard);
        }));
        return ok();
    }

    /**
     * 修改用户推广佣金比例
     * @param id
     * @param rewardScale
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateReward")
    @RequiresPermissions("sys:user:commission:rate")
    public ResultEntity upateReward(Integer id, BigDecimal rewardScale)throws Exception{
        if (!StringUtils.isNotBlank(id)||!StringUtils.isNotBlank(rewardScale)){
            throw new BussinessException("参数有误");
        }
        if (rewardScale.compareTo(BigDecimal.valueOf(100))>=0){
            throw new BussinessException("佣金比例不能超过100");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setRewardScale( rewardScale.setScale(2, BigDecimal.ROUND_HALF_DOWN));
        }));
        return ok();
    }

    /**
     * 添加推广人
     * @param id
     * @param parentId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("user/json/updateParent")
    @RequiresPermissions("sys:user:invite:edit")
    public ResultEntity updateParent(Integer id, Integer parentId)throws Exception{
        if (!StringUtils.isNotBlank(id)||!StringUtils.isNotBlank(parentId)){
            throw new BussinessException("参数有误");
        }
        userService.updateByPrimaryKeySelective(new User(u -> {
            u.setId(id);
            u.setParentId(parentId);
        }));
        return ok();
    }

    /**
     * 添加模拟投资人用户列表json数据
     */
    @ResponseBody
    @RequestMapping("user/json/simList")
    @RequiresPermissions("sys:user:list")
    public DtGrid simListJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager,Constants.USER);
        dtgrid  = userService.getDtGridList(dtgrid, UserModel.class);
        List<InvestorSimulate> list = investorSimulateService.select(new InvestorSimulate(t->{t.setDelFlag(InvestorSimulate.DELFLAG.NORMAL.code);}));
        List<Object> uList = dtgrid.getExhibitDatas();
        if( uList !=null &&  uList.size()>0){
            if(null != list && list.size()>0){
                Iterator<Object> iterator = uList.iterator();
                while (iterator.hasNext()) {
                    Object obj = iterator.next();
                    LinkedHashMap map = (LinkedHashMap) obj;
                    for (InvestorSimulate ivs:list) {
                        if((Integer)map.get("id")==ivs.getUserId()){
                            iterator.remove();
                        }
                    }
                }
            }
        }
        dtgrid.setExhibitDatas(uList);
        return dtgrid;
    }


    /**
     * 用户来源统计
     */
    @ResponseBody
    @RequestMapping("user/json/form")
    @RequiresPermissions("sys:user:form")
    public DtGrid statisticsJson(String dtGridPager) throws Exception {
        DtGrid dtgrid = dataAuthority(dtGridPager,null);
        return userService.getDtGridModelList(dtgrid);
    }

    /**
     * 用户来源统计导出
     * @param dtGridPager
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "userFrom/json/export", method = RequestMethod.POST)
    public ResultEntity exportSources(String dtGridPager, HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 执行导出
        ExportUtils.export(request, response,userService.getDtGridModelListExport(dtGridPager));
        return ok();
    }

}
